<template>
  <div class="container">
    <!-- 顶部导航 -->
    <div class="header-actions">
      <router-link to="/main/renshi/jixiao">返回绩效</router-link>
      <router-link to="/main/renshi/jixiao/nianyueList">列表</router-link>
    </div>
    <!-- 页面标题 -->
    <h2 class="page-title">
      <input style="width: 50px; height: 20px;" v-model="year">年
      <input style="width: 50px; height: 20px;" v-model="month">月工作计划与考核表
    </h2>
    <span style="display: flex;justify-content: flex-end;">
      <el-button v-if="!isView" type="primary" @click="saveData" class="save-button">保存</el-button>
    </span>
    <!-- 表单信息 -->
    <form class="form-info">
      <label>姓名：<input v-model="formData.name" :disabled="isView" /></label>
      <label>部门：<input v-model="formData.department" :disabled="isView" /></label>
      <label>岗位：<input v-model="formData.position" :disabled="isView" /></label>
    </form>
    <!-- 表格 -->
    <div class="table-container">
      <table border="1" style="text-align: center;">
        <thead>
          <tr>
            <th>序号</th>
            <th>类别</th>
            <th>月度主要工作任务</th>
            <th>计划达成的目标</th>
            <th>考核标准</th>
            <th>权重(%)</th>
            <th>实际达成</th>
            <th>自评得分</th>
            <th>上级评分</th>
            <th>备 注</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(detail, index) in formData.details" :key="index" :class="{ 'fade-in': !isView }">
            <td>{{ index + 1 }}</td>
            <td>{{ detail.categoryName }}</td>
            <td><input v-model="detail.monthlyTask" :disabled="isView" /></td>
            <td><input v-model="detail.plannedGoal" :disabled="isView" /></td>
            <td><input v-model="detail.evaluationCriteria" :disabled="isView" /></td>
            <td><input v-model="detail.weight" type="number" :disabled="isView" /></td>
            <td><input v-model="detail.actualAchievement" :disabled="isView" /></td>
            <td><input v-model="detail.selfScore" type="number" :disabled="isView" /></td>
            <td><input v-model="detail.superiorScore" type="number" :disabled="isView" /></td>
            <td><input v-model="detail.remark" :disabled="isView" /></td>
          </tr>
          <tr>
            <td colspan="5">合计（合计得分 = Σ 评分*权重）</td>
            <td>100%</td>
            <td></td>
            <td>{{ calculateTotalScore('self') }}</td>
            <td>{{ calculateTotalScore('superior') }}</td>
            <td></td>
          </tr>
        </tbody>
      </table>
      <table>
        <tbody>
          <tr>
            <td colspan="3">计划拟订：<input style="width: 60%;" v-model="formData.planMadeBy" :disabled="isView" /></td>
            <td colspan="2">直接上级：<input style="width: 60%;" v-model="formData.directSuperior" :disabled="isView" /></td>
            <td colspan="2">自&emsp;&emsp;评：<input style="width: 60%;" v-model="formData.selfAssessment"
                :disabled="isView" /></td>
            <td colspan="2">上级确认：<input style="width: 60%;" v-model="formData.superiorConfirmation"
                :disabled="isView" /></td>
          </tr>
          <tr>
            <td colspan="3">部长审核：<input style="width: 60%;" v-model="formData.ministerReview" :disabled="isView" /></td>
            <td colspan="2">人资确认：<input style="width: 60%;" v-model="formData.hrConfirmation" :disabled="isView" /></td>
            <td colspan="2">部长审核：<input style="width: 60%;" v-model="formData.ministerReviewAgain" :disabled="isView" />
            </td>
            <td colspan="2">人资确认：<input style="width: 60%;" v-model="formData.hrConfirmationAgain" :disabled="isView" />
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <!-- 表单底部信息 -->
    <div class="form-footer">
      <p>评分标准：</p>
      <p>100分----创造性、完全超乎预期地达成目标；</p>
      <p>95分----明显超越目标；</p>
      <p>90分----达成目标并有所超越；</p>
      <p>85分----基本达成目标，但有所不足；</p>
      <p>80分----与目标存在明显差距；</p>
      <p>0分----未进行此项工作。</p>

      <p>评分说明：评分低于75分时，要在备注栏或述职报告中进行说明。</p>
      <p>所有考核项目须将实际达成结果填入实际达成栏内。</p>
      <p style="display:flex;justify-content: space-between;padding:5px 0px;color:#757575;font-size:0.9em;">
        <span>表单编号及版本：AM-JY-096 A/3</span> <span>保存期限：长期</span>
      </p>

    </div>
  </div>
</template>

<script>
import { saveWorkPlanAssessment, getWorkPlanAssessmentDetail, getWorkPlanCategories, updateWorkPlanAssessment } from '@/api/workPlanAssessment'

export default {
  data() {
    return {
      year: '',
      month: '',
      isView: false,
      isEdit: false,
      formData: {
        id: null,
        name: '',
        department: '',
        position: '',
        details: [],
        planMadeBy: '',
        directSuperior: '',
        selfAssessment: '',
        superiorConfirmation: '',
        ministerReview: '',
        hrConfirmation: '',
        ministerReviewAgain: '',
        hrConfirmationAgain: ''
      },
      categories: null
    }
  },
  async created() {
    const { id, mode } = this.$route.query
    this.isView = mode === 'view'
    this.isEdit = mode === 'edit'

    try {
      // 先获取所有类别
      const categories = await getWorkPlanCategories()
      this.categories = categories.data

      if (id) {
        await this.fetchDetail(id)
      } else {
        await this.initializeDetails()
      }
    } catch (error) {
      this.$message.error('初始化数据失败：' + error.message)
    }
  },
  methods: {
    async initializeDetails() {
      if (!this.categories) return

      this.formData.details = this.categories.map(category => ({
        categoryId: category.id,
        categoryName: category.categoryName,
        monthlyTask: category.categoryName === '上级考核' ? '工作表现' : '',
        plannedGoal: category.categoryName === '上级考核' ? '上级/顾客满意度' : '',
        evaluationCriteria: '',
        weight: 0,
        actualAchievement: '',
        selfScore: 0,
        superiorScore: 0,
        remark: ''
      }))
    },
    async fetchDetail(id) {
      try {
        const detail = await getWorkPlanAssessmentDetail(id)
        console.log("detail", detail)

        // 设置基础信息
        this.year = detail.data.year.toString()
        this.month = detail.data.month.toString()

        // 先保存详情数据的其他字段
        const tempFormData = {
          ...detail.data,
          details: [] // 清空details，后面会重新设置
        }

        // 准备一个Map来存储已有的详情数据，方便查找
        const detailsMap = new Map()
        if (detail.data.details && Array.isArray(detail.data.details)) {
          detail.data.details.forEach(detail => {
            detailsMap.set(detail.categoryId, detail)
          })
        }

        // 使用类别列表作为基础，合并详情数据
        if (this.categories) {
          tempFormData.details = this.categories.map(category => {
            const existingDetail = detailsMap.get(category.id)
            if (existingDetail) {
              // 如果有对应的详情数据，合并并确保categoryName正确
              return {
                ...existingDetail,
                categoryId: category.id,
                categoryName: category.categoryName
              }
            }
            // 如果没有对应的详情数据，创建新的记录
            return {
              categoryId: category.id,
              categoryName: category.categoryName,
              monthlyTask: category.categoryName === '上级考核' ? '工作表现' : '',
              plannedGoal: category.categoryName === '上级考核' ? '上级/顾客满意度' : '',
              evaluationCriteria: '',
              weight: 0,
              actualAchievement: '',
              selfScore: 0,
              superiorScore: 0,
              remark: ''
            }
          })
        }

        // 更新表单数据
        this.formData = tempFormData

      } catch (error) {
        console.error('获取详情失败：', error)
        this.$message.error('获取详情失败：' + error.message)
      }
    },
    calculateTotalScore(type) {
      if (!this.formData.details) return 0
      return this.formData.details.reduce((sum, detail) => {
        const score = type === 'self' ? detail.selfScore : detail.superiorScore
        const weight = detail.weight || 0
        return sum + (score || 0) * (weight / 100)
      }, 0).toFixed(2)
    },
    async saveData() {
      try {
        if (!this.formData.name) throw new Error('请填写姓名')
        if (!this.formData.department) throw new Error('请填写部门')
        if (!this.formData.position) throw new Error('请填写岗位')
        if (!this.year) throw new Error('请选择年份')
        if (!this.month) throw new Error('请选择月份')

        const assessment = {
          ...this.formData,
          year: parseInt(this.year),
          month: parseInt(this.month)
        }

        if (this.isEdit) {
          await updateWorkPlanAssessment(assessment)
        } else {
          await saveWorkPlanAssessment(assessment)
        }

        this.$message.success('保存成功')
        this.$router.push('/main/renshi/jixiao/nianyueList')
      } catch (error) {
        this.$message.error('保存失败：' + error.message)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/* 容器样式 */
.container {
  padding: 12px;
  // background-color: #f9f9f9;
  border-radius: 4px;
  // box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  min-height: calc(100vh - 24px);
  // overflow: auto;
  width: 1200px;
  margin: 0 auto;
}

/* 顶部导航样式 */
.header-actions {
  display: flex;
  justify-content: flex-start;
  gap: 12px;
  margin-bottom: 12px;

  a {
    color: #409EFF;
    text-decoration: none;
    font-size: 14px;

    &:hover {
      color: #66b1ff;
    }
  }
}

/* 页面标题样式 */
.page-title {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
  font-size: 18px;
  color: #2c3e50;
  font-weight: 500;

  input {
    width: 40px;
    height: 24px;
    text-align: center;
    margin: 0 4px;
    border: 1px solid #dcdfe6;
    border-radius: 3px;

    &:focus {
      border-color: #409EFF;
      outline: none;
    }
  }
}

/* 表单信息样式 */
.form-info {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  white-space: nowrap;
  align-items: center;
  background: #fff;
  padding: 12px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);

  label {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    color: #606266;

    input {
      width: 110px;
      height: 28px;
      border: 1px solid #dcdfe6;
      border-radius: 3px;
      padding: 0 8px;
      font-size: 14px;

      &:focus {
        border-color: #409EFF;
        outline: none;
      }

      &[disabled] {
        background-color: #f5f7fa;
        border-color: #e4e7ed;
        color: #606266;
        cursor: not-allowed;
      }
    }
  }
}

.save-button {
  position: relative;
  padding: 8px 16px;
  font-size: 14px;
  margin-bottom: 10px;
}

/* 表格容器样式 */
.table-container {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  overflow-x: auto;
  // margin-bottom: 16px;

  table {
    border-collapse: collapse;
    width: 100%;
    font-size: 14px;

    th,
    td {
      border: 1px solid #ebeef5;
      padding: 8px;
      height: 40px;
      text-align: center;
    }

    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: 500;
      white-space: nowrap;
    }

    td {
      input {
        width: 83%;
        height: 28px;
        border: 1px solid #dcdfe6;
        border-radius: 3px;
        padding: 0 8px;
        font-size: 14px;

        &:focus {
          border-color: #409EFF;
          outline: none;
        }

        &[disabled] {
          background-color: #f5f7fa;
          border-color: #e4e7ed;
          color: #606266;
          cursor: not-allowed;
        }

        &[type="number"] {
          text-align: right;
        }
      }
    }

    tr:hover {
      background-color: #f5f7fa;
    }
  }
}

/* 表单底部信息样式 */
.form-footer {
  background: #fff;
  border-radius: 4px;
  padding: 12px 16px;
  // margin-top: 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);

  p {
    margin: 8px 0;
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
    text-indent: 28px;
    text-align: left;

    &:first-child {
      text-indent: 0;
      font-weight: 500;
      margin-bottom: 12px;
    }
  }
}

/* 淡入动画 */
.fade-in {
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 表单编号样式 */
.form-number {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  color: #909399;
  font-size: 13px;
}
</style>